package com.tbs.easyhomemoneyserver.interfaces.impl;

import com.tbs.easyhomemoneyserver.DO.ApiLimit;
import com.tbs.easyhomemoneyserver.constants.BeanNameConstants;
import com.tbs.easyhomemoneyserver.constants.CommonConstants;
import com.tbs.easyhomemoneyserver.interfaces.IRightAuthorization;
import com.tbs.easyhomemoneyserver.model.ApiRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Set;

/**
 * @author tongj
 */
@Component(BeanNameConstants.CONTAIN_RIGHTS_AUTH)
@Slf4j
public class SimpleContainsAuth implements IRightAuthorization {
    @Override
    public boolean auth(ApiLimit limit, HttpServletRequest request, ApiRequest apiRequest) {
        if (!CommonConstants.ENABLE.equals(limit.getForceNeedFlag())) {
            return true;
        }
        Set<String> userRights = apiRequest.getUserOwnsRights().get(limit.getRoleType());
        return userRights.contains(limit.getRole());
    }

    @Override
    public String unAuthedText(ApiRequest request, ApiLimit noPassRights) {
        return String.format("用户 %s 不存在权限:%s 权限备注:%s", request.getUserInfo() == null ? "未登录用户" : request.getUserInfo().getName(), noPassRights.getRole(), noPassRights.getComment());
    }
}
